package com.bsoft.gol.hcs.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

public class DateTimeUtil {

    /**
     * 根据指定时间获取年龄
     *
     * @param date
     * @return
     */
    public static Integer getAge(Date date) {
        Date now = new Date();

        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(now);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date);

        return cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
    }

//    /**
//     * 根据出生日期获取年龄
//     *
//     * @param birthday
//     * @return java.lang.String
//     * @throws
//     * @author tongtp
//     * @date 2020/12/11 11:23
//     */
//    public static String getAge(Date birthday) {
//        long days = (System.currentTimeMillis() - birthday.getTime()) / (24 * 60 * 60 * 1000);
//        if (days <= 0) {
//            return "1天";
//        }
//        if (days < 30) {
//            return days + "天";
//        }
//        Calendar now = Calendar.getInstance();
//        Calendar birthdayCalendar = Calendar.getInstance();
//        birthdayCalendar.setTime(birthday);
//        int months = now.get(Calendar.MONTH) - birthdayCalendar.get(Calendar.MONTH);
//        int years = now.get(Calendar.YEAR) - birthdayCalendar.get(Calendar.YEAR);
//        if (months <= 0) {
//            years--;
//            months += 12;
//        }
//        if (days < 365) {
//            int dayOfMonth = now.get(Calendar.DAY_OF_MONTH) - birthdayCalendar.get(Calendar.DAY_OF_MONTH);
//            if (dayOfMonth < 0) {
//                months--;
//                dayOfMonth += 30;
//            }
//            return months + "月" + (dayOfMonth > 0 ?
//                    dayOfMonth + "天" : "");
//        }
//        if (months == 12) {
//            years++;
//            months = 0;
//        }
//        return years + "岁" + (months > 0 ? months + "月" : "");
//    }

    public static String strDate(Date datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        return f.format(datetime);
    }

    /*
     * 判断yyyy-MM-dd日期是否是今天
     */
    public static boolean isToday(String datetime) {
        Date nowTime = new Date();
        //获取今天的日期
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sf.format(nowTime);
        return datetime.equals(today);
    }

    public static boolean isToday(Date datetime) {
        Date nowTime = new Date();
        //获取今天的日期
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String datetimeStr = sf.format(datetime);
        String today = sf.format(nowTime);
        return datetimeStr.equals(today);
    }

    /*
     * 获取今天yyyy-MM-dd格式的日期
     */
    public static String getTodayString() {
        Date nowTime = new Date();
        //获取今天的日期
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sf.format(nowTime);
        return today;
    }

    /*
     * 两个时间相差的分钟数,默认data2大于data1
     */
    public static long hoursBetweenTwoTimes(Date data1, Date data2) {
        long interval = (data2.getTime() - data1.getTime()) / 1000 / 60 / 60;
        return interval;
    }

    /*
     * 两个时间相差的分钟数,默认data2大于data1
     */
    public static long minutesBetweenTwoTimes(Date data1, Date data2) {
        long interval = (data2.getTime() - data1.getTime()) / 1000 / 60;
        return interval;
    }

    /*
     * 两个时间相差的秒数,默认data2大于data1
     */
    public static long secondBetweenTwoTimes(Date data1, Date data2) {
        long interval = (data2.getTime() - data1.getTime()) / 1000;
        return interval;
    }

    /*
     * 计算云诊室预约挂号剩余的支付时间，data1为预约时间，data2为当前时间，overTime为云诊室预约支付超时时间的时间间隔，单位秒
     */
    public static long secondBetweenTwoTimesForAppointment(Date data1, Date data2, int overTime) {
        long interval = (data1.getTime() + overTime * 1000 - data2.getTime()) / 1000;
        if (interval <= 0) {
            interval = 0;
        }
        return interval;
    }

    /*
     * 获取今天yyyy-MM-dd格式的日期
     */
    public static Date getTodayDate() {
        return new Date();
    }

    public static DateFormat format6 = new SimpleDateFormat("yyyyMMddHHmmss");


    /**
     * yyyy-MM-dd HH:mm:ss  格式转DATA
     *
     * @Author:FangZhiyi
     * @Description
     * @Params [data]
     * @Return java.util.Date
     * @Data Created in 2019/1/14
     * @Moddified By:
     */
    public static Date getDate(String data) {
        SimpleDateFormat format = null;
        if (data.length() == 10) {
            format = new SimpleDateFormat("yyyy-MM-dd");
        } else {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        try {
            return format.parse(data);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date();
    }

    /**
     * 根据身份证算年龄
     *
     * @Author:FangZhiyi
     * @Description
     * @Params [IdNO]
     * @Return int
     * @Data Created in 2019/1/14
     * @Moddified By:
     */
    public static int IdNOToAge(String IdNO) {
        int leh = IdNO.length();
        String dates = "";
        if (leh == 18) {
            int se = Integer.valueOf(IdNO.substring(leh - 1)) % 2;
            dates = IdNO.substring(6, 10);
            SimpleDateFormat df = new SimpleDateFormat("yyyy");
            String year = df.format(new Date());
            int u = Integer.parseInt(year) - Integer.parseInt(dates);
            return u;
        } else {
            dates = IdNO.substring(6, 8);
            return Integer.parseInt(dates);
        }

    }


    /**
     * 根据出生日期算年龄
     *
     * @Author:FangZhiyi
     * @Description
     * @Params [birthday]
     * @Return int
     * @Data Created in 2019/1/14
     * @Moddified By:
     */
    public static int getAgeByBirth(Date birthday) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间
            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);
            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }

    public static Date computingTime(Date date, int year, int month, int day, int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (year != 0) {
            calendar.add(1, year);//1对年份操作
        }
        if (month != 0) {
            calendar.add(2, month);//2是对月份操作
        }
        if (day != 0) {
            calendar.add(5, day);//5，6是对日期操作
        }
        if (hour != 0) {
            calendar.add(11, hour);//11是对小时操作
        }
        if (minute != 0) {
            calendar.add(12, minute);//12是对分钟操作
        }
        if (second != 0) {
            calendar.add(13, second);//13是对秒操作
        }
        return calendar.getTime();
    }

    public static Date stringToDate(String date, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        try {
            return dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date();
    }

    /*获取两个日期相差的天数,date1为小值，data2为大值，否则返回负数*/
    public static long differentDays(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            throw new RuntimeException("日期不能为空");
        }
        LocalDate localDate1 = date2LocalDate(date1);
        LocalDate localDate2 = date2LocalDate(date2);
        return localDate1.until(localDate2, ChronoUnit.DAYS);
    }

    public static LocalDate date2LocalDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = instant.atZone(zoneId).toLocalDate();
        return localDate;
    }

    /*判两段时间是否有交集*/
    public static boolean isOverlap(Date leftStartDate, Date leftEndDate, Date rightStartDate, Date rightEndDate) {
        return
                ((leftStartDate.getTime() >= rightStartDate.getTime())
                        && leftStartDate.getTime() < rightEndDate.getTime())
                        ||
                        ((leftStartDate.getTime() > rightStartDate.getTime())
                                && leftStartDate.getTime() <= rightEndDate.getTime())
                        ||
                        ((rightStartDate.getTime() >= leftStartDate.getTime())
                                && rightStartDate.getTime() < leftEndDate.getTime())
                        ||
                        ((rightStartDate.getTime() > leftStartDate.getTime())
                                && rightStartDate.getTime() <= leftEndDate.getTime());

    }


    /**
     * 判断两个时间范围是否有交集,
     * 结束时间和开始时间相同认为没有交集
     * 开始时间小于结束时间
     *
     * @param dynaStartTime  比较时间段开始时间
     * @param dynaEndTime    比较时间段结束时间
     * @param fixedStartTime 参考时间段开始时间
     * @param fixedEndTime   参考时间段结束时间
     * @return
     */
    public static Boolean checkTimesHasOverlap(Date dynaStartTime, Date dynaEndTime, Date fixedStartTime,
                                               Date fixedEndTime) {
        return !(dynaEndTime.getTime() <= fixedStartTime.getTime() || dynaStartTime.getTime() >= fixedEndTime.getTime());
    }

    //班别  1上午2下午3晚上
    public static byte getTimeFlag(Date date) {
        byte timeFlag = 0;
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String str = df.format(date);
        int a = Integer.parseInt(str);
        if (a >= 0 && a < 12) {
            timeFlag = 1;//上午
        } else if (a >= 12 && a < 18) {
            timeFlag = 2;//下午
        } else if (a >= 18 && a < 24) {
            timeFlag = 3;//晚上
        }
        return timeFlag;
    }

    /**
     * 获取两个时间中大的(晚的)那个,其中一个为null，直接返回另一个，都为null，返回null
     *
     * @param date1
     * @param date2
     * @return java.util.Date
     * @throws
     * @author tongtp
     * @date 2022/6/1 9:47
     */
    public static Date getMaxDate(Date date1, Date date2) {
        if (date1 == null) {
            return date2;
        }
        if (date2 == null) {
            return date1;
        }
        if (date1.after(date2)) {
            return date1;
        } else {
            return date2;
        }
    }

    /**
     * 获取两个时间中小的(早的)那个,其中一个为null，直接返回另一个，都为null，返回null
     *
     * @param date1
     * @param date2
     * @return java.util.Date
     * @throws
     * @author tongtp
     * @date 2022/6/1 9:47
     */
    public static Date getMinDate(Date date1, Date date2) {
        if (date1 == null) {
            return date2;
        }
        if (date2 == null) {
            return date1;
        }
        if (date1.after(date2)) {
            return date2;
        } else {
            return date1;
        }
    }

}
